/**
 * Copyright (C) 2008 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.dao.db.utils.logic;

import static cc.aileron.commons.accessor.PojoAccessorModule.defaultFactory;
import cc.aileron.commons.accessor.PojoAccessor;
import cc.aileron.dao.db.Id;

/**
 * Id�A�m�e�[�V������t�^�����I�u�W�F�N�g��equals���\�b�h����������ׂ�Utils�N���X
 * 
 * @author Aileron
 * 
 */
public class DbDtoEqualsUtils
{
    /**
     * DbDtoEqualsUtils.equals ���s�\�ȏꍇ
     * 
     * @author Aileron
     * 
     */
    public static class NoComparison extends Error
    {
        /**
         * serialVersionUID
         */
        private static final long serialVersionUID = -511851860415556161L;

        /**
         * @param object
         */
        public NoComparison(final Object object)
        {
            super(object.toString());
        }

    }

    /**
     * Id�A�m�e�[�V�����Ŏw�肳��Ă���v���p�e�B�̒l���g���� �����I�u�W�F�N�g�ŗL�邩���r����
     * 
     * @param target
     * @param comparison
     * @return �����I�u�W�F�N�g�ň��邩
     */
    public static boolean idEquals(final Object target, final Object comparison)
    {
        if (target == null || comparison == null)
        {
            return false;
        }
        if (!target.getClass().equals(comparison.getClass()))
        {
            return false;
        }
        final Id id = target.getClass().getAnnotation(Id.class);
        if (id == null)
        {
            throw new NoComparison(target);
        }

        final PojoAccessor<Object> targetAccessor = defaultFactory
                .accessor(target);

        final PojoAccessor<Object> comparisonAccessor = defaultFactory
                .accessor(comparison);

        final Number targetIdValue = targetAccessor.getNumber(id.value());
        if (targetIdValue.intValue() == 0)
        {
            throw new NoComparison(target);
        }

        final Number comparisonIdValue = comparisonAccessor.getNumber(id
                .value());
        if (comparisonIdValue.intValue() == 0)
        {
            throw new NoComparison(comparison);
        }

        return targetIdValue.equals(comparisonIdValue);
    }

    /**
     * �X�^�e�B�b�N��Utils�N���X�̈׃C���X�^���X�������Ȃ�
     */
    private DbDtoEqualsUtils()
    {
    }
}
